import EaseInOut from '@/libs/easeInOut'
import {str2num} from '@/libs/toolkit'
import type {ActionContext} from 'vuex'
import {RootState} from '.'

export type LayoutMainState = {}
export type LayoutMainContext = ActionContext<LayoutMainState, RootState>

const state: LayoutMainState = {}

const mutations = {}

const actions = {
  MAINSCROLLTO(ctx: LayoutMainContext, targetId: string) {
    const main = document.getElementById('CBC-main')
    if (targetId) {
      const targetDom = document.getElementById(targetId)
      const targetoffsetTop = targetDom?.offsetTop || 0
      if (main) {
        const scrollTop = main.scrollTop
        console.log('目标元素的offsetTop', scrollTop, targetoffsetTop, targetId, targetDom)
        new EaseInOut({
          autoplay: true,
          startVal: scrollTop,
          endVal: targetoffsetTop,
          duration: 500,
          running(val) {
            main?.scrollTo(targetoffsetTop, str2num(val) || 0)
          }
        })
      }
    }
  },
  MAINSCROLLTOTOP(ctx: LayoutMainContext, targetId: string) {
    const main = document.getElementById('CBC-main')
    let targetoffsetHeight = 0
    if (targetId) {
      const targetDom = document.getElementById(targetId)
      targetoffsetHeight = targetDom?.offsetHeight || 0
      if (main) {
        const scrollTop = targetoffsetHeight || main.scrollTop
        console.log('目标元素的offsetHeight', scrollTop, targetoffsetHeight, main.scrollTop)
        if (!scrollTop || scrollTop <= 0) return
        new EaseInOut({
          autoplay: true,
          startVal: scrollTop,
          endVal: 0,
          duration: 500,
          running(val) {
            main?.scrollTo(0, str2num(val) || 0)
          }
        })
      }
    }
  }
}

const getters = {}

export default {
  namespaced: true, // 声明命名空间
  state,
  mutations,
  actions,
  getters
}
